package com.liyongjian.xhban.dal;

import java.util.List;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.liyongjian.xhban.model.AccountGroup;
import com.liyongjian.xhban.model.Group;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.emumm.BlogType;
import com.liyongjian.xhban.model.emumm.LiveDieState;
import com.liyongjian.xhban.model.emumm.YesNoState;

public interface AccountGroupRepository extends PagingAndSortingRepository<AccountGroup, Long> {

    List<AccountGroup> findByUserIdAndState(Long userId, LiveDieState state);

    @Query("select t from AccountGroup t ,Group g where t.groupId=g.id and t.userId=:userId and t.state=:state and g.type=:type and g.state=1 and g.isSealed=:isSealed")
    List<AccountGroup> findByUserIdAndTypeAndState(@Param("userId") Long userId,
            @Param("type") BlogType type, @Param("state") LiveDieState state,
            @Param("isSealed") YesNoState isSealed);

    @Query("select t from AccountGroup t, Group g where t.groupId=g.id and t.userId=:userId and t.state=1 and g.state=1 and g.isSealed=0")
    List<AccountGroup> findAccountGroupByUserId(@Param("userId") Long userId);

    @Query("select g from AccountGroup t, Group g where t.groupId=g.id and t.userId=:userId and t.state=1 and g.state=1")
    List<Group> findGroupByUserId(@Param("userId") Long userId);

    @Query("select u from AccountGroup t, User u where t.userId=u.id and t.groupId=:groupId and t.state=1 and u.state=1")
    List<User> findUserByGroupId(@Param("groupId") Long groupId);

    @Query("select t from AccountGroup t where t.groupId=:groupId and t.state=1")
    List<AccountGroup> findByGroupId(@Param("groupId") Long groupId);

    AccountGroup findByUserIdAndIsDefaultAndState(Long userId, Boolean isDefault,
            LiveDieState state);

    AccountGroup findByUserIdAndGroupIdAndState(Long userId, Long groupId, LiveDieState state);

    @Query("select t.userId from AccountGroup t where t.groupId=:groupId and t.state=1")
    List<Long> findUserIdByGroupId(@Param("groupId") Long groupId);


    @Modifying
    @Query("update AccountGroup set payMoney=payMoney+:money where userId=:userId and groupId=:groupId and state=1")
    int updatePayMoneyByUserIdAndGroupId(@Param("userId") Long userId,
            @Param("groupId") Long groupId, @Param("money") Float money);

    @Modifying
    @Query("update AccountGroup set money=money+:money where userId=:userId and groupId=:groupId and state=1")
    int updateMoneyByUserIdAndGroupId(@Param("userId") Long userId, @Param("groupId") Long groupId,
            @Param("money") Float money);


    @Modifying
    @Query("update AccountGroup set isDefault=0 where userId=:userId and state=1")
    int updateIsDefaultByUserId(@Param("userId") Long userId);

}
